package com.test.base.api;

import com.test.base.dao.NideshopAddressDao;
import com.test.base.dao.NideshopCartDao;
import com.test.base.dao.NideshopGoodsDao;
import com.test.base.dao.NideshopProductDao;
import com.test.base.entity.*;
import com.test.base.service.CartService;
import com.test.base.service.GoodsSepcifitionService;
import com.test.base.service.RegionService;
import com.test.base.utils.Assist;
import com.test.base.vo.api.AddressEtxVo;
import com.test.base.vo.api.CartCheckoutVo;
import com.test.base.vo.api.CartVo;
import com.test.base.vo.common.ResultData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "api/cart")
@Api(description = "购物车接口")
public class CartApi {

    @Autowired
    private CartService cartService;
    @Autowired
    private NideshopGoodsDao nideshopGoodsDao;
    @Autowired
    private NideshopProductDao nideshopProductDao;
    @Autowired
    private NideshopCartDao nideshopCartDao;
    @Autowired
    private GoodsSepcifitionService goodsSepcifitionService;
    @Autowired
    private NideshopAddressDao nideshopAddressDao;
    @Autowired
    private RegionService regionService;

    @ApiOperation(value = "获取Cart", notes = "")
    @RequestMapping(value = "/cart", method = RequestMethod.GET)
    @ResponseBody
    @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query", required = true, dataType = "Long")
    public ResultData<CartVo> getCart(Long userId) {
        return new ResultData<CartVo>(cartService.getCart(userId), null, true);
    }


    @ApiOperation(value = "添加到购物车", notes = "")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "goodsId", value = "商品ID", required = true, paramType = "query", dataType = "Long", defaultValue = "1"),
            @ApiImplicitParam(name = "productId", value = "产品ID", required = true, paramType = "query", dataType = "Long", defaultValue = "10"),
            @ApiImplicitParam(name = "number", value = "数量", required = true, paramType = "query", dataType = "Integer", defaultValue = "10")
    })
    public ResultData add(Long userId, Long goodsId, Long productId, Integer number) {
        // 判断商品是否可以购买
        NideshopGoods goodsInfo = nideshopGoodsDao.selectNideshopGoodsById(goodsId);
        if (null == goodsInfo || goodsInfo.getIsDelete() == 1) {
            return new ResultData(400, "商品已下架");
        }
        // 取得规格的信息,判断规格库存
        NideshopProduct productInfo = nideshopProductDao.selectNideshopProductById(productId);
        if (null != productInfo && productInfo.getGoodsNumber() < number) {
            return new ResultData(400, "库存不足");
        }
        NideshopCart cartFind = new NideshopCart();
        cartFind.setGoodsId(goodsId);
        cartFind.setProductId(productId);
        NideshopCart cartInfo = nideshopCartDao.selectNideshopCartByObj(cartFind);
        int row = 0;//更新或者添加影响行数
        if (null == cartInfo) {
            // 添加规格名和值
            String goodsSepcifitionValue = goodsSepcifitionService.get(goodsId, productInfo.getGoodsSpecificationIds().split("_"));
            NideshopCart cart = new NideshopCart();
            cart.setGoodsId(goodsId);
            cart.setProductId(productId);
            cart.setGoodsSn(productInfo.getGoodsSn());
            cart.setGoodsName(goodsInfo.getName());
            cart.setListPicUrl(goodsInfo.getListPicUrl());
            cart.setNumber(number.longValue());
            cart.setSessionId("1");
            cart.setUserId(userId);
            cart.setRetailPrice(productInfo.getRetailPrice());
            cart.setMarketPrice(productInfo.getRetailPrice());
            cart.setGoodsSpecifitionNameValue(goodsSepcifitionValue);
            cart.setGoodsSpecifitionIds(productInfo.getGoodsSpecificationIds());
            cart.setChecked(1);
            nideshopCartDao.insertNideshopCart(cart);
        } else {
            Long upNumber = number + cartInfo.getNumber();
            if (null != productInfo && productInfo.getGoodsNumber() < upNumber) {
                return new ResultData(400, "库存不足");
            }
            cartInfo.setNumber(upNumber);
            Assist cartUpdate = new Assist();
            cartUpdate.setRequires(Assist.andEq("goods_id", goodsId));
            cartUpdate.setRequires(Assist.andEq("product_id", productId));
            cartUpdate.setRequires(Assist.andEq("id", cartInfo.getId()));
            nideshopCartDao.updateNideshopCart(cartInfo, cartUpdate);
        }
        return new ResultData<CartVo>(cartService.getCart(userId));
    }


    @ApiOperation(value = "更新指定的购物车信息", notes = "")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "id", value = "购物车ID", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "productId", value = "产品ID", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "number", value = "数量", required = true, paramType = "query", dataType = "Integer")
    })
    public ResultData update(Long id, Long userId, Long productId, Integer number) {
        // 取得规格的信息,判断规格库存
        NideshopProduct productInfo = nideshopProductDao.selectNideshopProductById(productId);
        if (null != productInfo && productInfo.getGoodsNumber() < number) {
            return new ResultData(400, "库存不足");
        }
        NideshopCart cartInfo = nideshopCartDao.selectNideshopCartById(id);
        if (cartInfo.getProductId().equals(productId)) {
            cartInfo.setNumber(number.longValue());
            nideshopCartDao.updateNideshopCartById(cartInfo);
        }
        return new ResultData<CartVo>(cartService.getCart(userId));
    }

    @ApiOperation(value = "是否选择商品", notes = "是否选择商品，如果已经选择，则取消选择，批量操作")
    @RequestMapping(value = "/checked", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "productIds", value = "产品ID集合用，分隔", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isChecked", value = "选中的状态", required = true, paramType = "query", dataType = "Integer"),

    })
    public ResultData checked(Long userId, String productIds, Integer isChecked) {
        if (StringUtils.isEmpty(productIds)) {
            return new ResultData(400, "操作失败");
        }
        NideshopCart upCart = new NideshopCart();
        upCart.setChecked(isChecked);
        Assist assist = new Assist();
        assist.setRequires(Assist.andEq("user_id", userId));
        assist.setRequires(Assist.customRequire("in (", productIds, ")"));
        nideshopCartDao.updateNonEmptyNideshopCart(upCart, assist);
        return new ResultData<CartVo>(cartService.getCart(userId));
    }

    @ApiOperation(value = "删除选中的购物车商品", notes = "批量删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "productIds", value = "产品ID集合用，分隔", paramType = "query", required = true, dataType = "String")
    })
    public ResultData delete(Long userId, String productIds) {
        if (StringUtils.isEmpty(productIds)) {
            return new ResultData(400, "删除出错");
        }
        Assist assist = new Assist();
        assist.setRequires(Assist.andEq("user_id", userId));
        assist.setRequires(Assist.customRequire("in (", productIds, ")"));
        nideshopCartDao.deleteNideshopCart(assist);
        return new ResultData<CartVo>(cartService.getCart(userId));
    }

    @ApiOperation(value = "获取购物车商品的总件件数", notes = "")
    @RequestMapping(value = "/goodsCount", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query", required = true, dataType = "Long")
    })
    public ResultData goodsCount(Long userId) {
        return new ResultData<Integer>(cartService.getGoodsList(userId).size());
    }

    @ApiOperation(value = "订单提交前的检验和填写相关订单信息", notes = "")
    @RequestMapping(value = "/checkout", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "addressId", value = "用户ID", paramType = "query", required = true, dataType = "Long")
    })
    public ResultData checkout(Long userId, Long addressId) {
        NideshopAddress checkedAddress;
        // 获取收货地址 没有就选择默认的
        if (null == addressId) {
            NideshopAddress findObject = new NideshopAddress();
            findObject.setIsDefault(1);
            findObject.setUserId(userId);
            checkedAddress = nideshopAddressDao.selectNideshopAddressByObj(findObject);
        } else {
            NideshopAddress findObject = new NideshopAddress();
            findObject.setId(addressId);
            findObject.setUserId(userId);
            checkedAddress = nideshopAddressDao.selectNideshopAddressByObj(findObject);
        }
        AddressEtxVo addressVo = new AddressEtxVo();
        if (null != checkedAddress) {
            BeanUtils.copyProperties(checkedAddress, addressVo);
            addressVo.setCityName(regionService.getRegionName(checkedAddress.getCityId()));
            addressVo.setDistrictName(regionService.getRegionName(checkedAddress.getDistrictId()));
            addressVo.setProvinceName(regionService.getRegionName(checkedAddress.getProvinceId()));
        }
        // 根据收货地址计算运费
        double freightPrice = 0.00;
        List<NideshopCart> checkCartList = new ArrayList<>();
        CartVo cartVo = cartService.getCart(userId);
        for (NideshopCart c : cartVo.getCartList()) {
            if (c.getChecked().equals(1)) {
                checkCartList.add(c);
            }
        }
        // 获取可用的优惠券信息，功能还未实现
        List<NideshopCoupon> nideshopCoupon = new ArrayList<>(0);
        double couponPrice = 0.00; // 使用优惠券减免的金额

        double goodsTotalPrice = cartVo.getCartTotal().getCheckedGoodsAmount(); // 商品总价
        double orderTotalPrice = cartVo.getCartTotal().getCheckedGoodsAmount() + freightPrice - couponPrice; // 订单的总价
        double actualPrice = orderTotalPrice - 0.00; // 减去其它支付的金额后，要实际支付的金额
        CartCheckoutVo checkoutVo = new CartCheckoutVo();
        checkoutVo.setCheckedAddress(addressVo);
        checkoutVo.setFreightPrice(freightPrice);
        checkoutVo.setCouponList(nideshopCoupon);
        checkoutVo.setCouponPrice(couponPrice);
        checkoutVo.setCheckedGoodsList(checkCartList);
        checkoutVo.setGoodsTotalPrice(goodsTotalPrice);
        checkoutVo.setOrderTotalPrice(orderTotalPrice);
        checkoutVo.setActualPrice(actualPrice);
        return new ResultData(checkCartList);
    }

}
